package com.zx.zxapibackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zx.zxapibackend.annotation.AuthCheck;
import com.zx.zxapibackend.common.DeleteRequest;
import com.zx.zxapibackend.common.IdRequest;
import com.zx.zxapibackend.constant.UserConstant;
import com.zx.zxapibackend.exception.ThrowUtils;
import com.zx.zxapibackend.mapper.AuthMapper;
import com.zx.zxapibackend.model.domain.InterfaceCharging;
import com.zx.zxapibackend.model.domain.User;
import com.zx.zxapibackend.model.dto.interfaceInfo.InterfaceInfoAddRequest;
import com.zx.zxapibackend.model.dto.interfaceInfo.InterfaceInfoQueryRequest;
import com.zx.zxapibackend.model.dto.interfaceInfo.InterfaceInfoUpdateRequest;
import com.zx.zxapibackend.model.enums.InterfaceInfoStatusEnum;
import com.zx.zxapibackend.model.vo.AllInterfaceInfoVo;
import com.zx.zxapibackend.model.vo.InterfaceInfoVO;
import com.zx.zxapibackend.service.InterfaceChargingService;
import com.zx.zxapibackend.service.InterfaceInfoService;
import com.zx.zxapibackend.service.UserInterfaceInfoService;
import com.zx.zxapibackend.service.UserService;
import com.zx.zxapiclientsdk.client.ZxAPIClient;
import com.zx.zxapicommon.common.BaseResponse;
import com.zx.zxapicommon.exception.BusinessException;
import com.zx.zxapicommon.model.entity.InterfaceInfo;
import com.zx.zxapicommon.model.entity.UserInterfaceInfo;
import com.zx.zxapicommon.model.enums.ErrorCode;
import com.zx.zxapicommon.model.to.GetAvailablePiecesTo;
import com.zx.zxapicommon.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 接口信息
 *
 * @author 张旭
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private InterfaceChargingService interfaceChargingService;

    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;

    @Resource
    private UserService userService;

    @Resource
    private AuthMapper authMapper;

    @Resource
    private ZxAPIClient zxAPIClient;


    /**
     * 创建
     *
     * @param interfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @Transactional
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);

        //校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        //存储接口信息
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());
        boolean result = interfaceInfoService.save(interfaceInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        //存储接口收费信息
        InterfaceCharging interfaceCharging = new InterfaceCharging();
        interfaceCharging.setInterfaceId(interfaceInfo.getId());
        interfaceCharging.setCharging(interfaceInfoAddRequest.getCharging());
        interfaceCharging.setAvailablePieces(interfaceInfoAddRequest.getAvailablePieces());
        interfaceCharging.setUserId(loginUser.getId());
        interfaceChargingService.save(interfaceCharging);


        long newInterfaceInfoId = interfaceInfo.getId();
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @Transactional
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0L) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(oldInterfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        boolean interfaceId = interfaceChargingService.remove(new QueryWrapper<InterfaceCharging>().eq("interfaceId", id));
        boolean result = b && interfaceId;
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return ResultUtils.success(result);
    }

    /**
     * 更新（仅管理员）
     *
     * @param interfaceInfoUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @Transactional
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest) {
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);

        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(oldInterfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);
        //更新接口信息表
        boolean result1 = interfaceInfoService.updateById(interfaceInfo);

        //更新接口收费表
        Double charging = interfaceInfoUpdateRequest.getCharging();
        String availablePieces = interfaceInfoUpdateRequest.getAvailablePieces();

        if (charging == null || charging < 0.0 || StringUtils.isBlank(availablePieces)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }


        UpdateWrapper<InterfaceCharging> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("interfaceId", id);
        updateWrapper.set("availablePieces", availablePieces);
        updateWrapper.set("charging", charging);
        boolean result2 = interfaceChargingService.update(updateWrapper);


        return ResultUtils.success(result1 && result2);

    }

    /**
     * 根据id获取 点击查看接口
     * 获取接口的详细信息和用户调用次数
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<InterfaceInfoVO> getInterfaceInfo(InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        if (interfaceInfoQueryRequest.getId() <= 0L) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //获取接口信息
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(interfaceInfoQueryRequest.getId());
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        InterfaceInfoVO interfaceInfoVO = new InterfaceInfoVO();
        BeanUtils.copyProperties(interfaceInfo, interfaceInfoVO);

        //获取用户剩余调用次数
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<UserInterfaceInfo> userInterfaceInfoQueryWrapper = new QueryWrapper<>();
        userInterfaceInfoQueryWrapper.eq("interfaceInfoId", interfaceInfo.getId());
        userInterfaceInfoQueryWrapper.eq("userId", loginUser.getId());
        UserInterfaceInfo one = userInterfaceInfoService.getOne(userInterfaceInfoQueryWrapper);
        if (null == one) {
            UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
            userInterfaceInfo.setUserId(loginUser.getId());
            userInterfaceInfo.setInterfaceInfoId(interfaceInfo.getId());
            userInterfaceInfoService.save(userInterfaceInfo);
            interfaceInfoVO.setLeftNum(0);
        } else {
            interfaceInfoVO.setLeftNum(one.getLeftNum());
        }

        return ResultUtils.success(interfaceInfoVO);


    }

    /**
     * 分页获取已上线的接口列表
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<AllInterfaceInfoVo>> listInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest,
                                                                          HttpServletRequest request) {

        if (null == interfaceInfoQueryRequest) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);


        return interfaceInfoService.listInterfaceInfoByPage(interfaceInfoQueryRequest);
    }

    @GetMapping("/list/AllPage")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Page<AllInterfaceInfoVo>> getAllInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        if (null == interfaceInfoQueryRequest) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return interfaceInfoService.getAllInterfaceInfoPage(interfaceInfoQueryRequest, request);
    }

    /**
     * 上线接口
     *
     * @param idRequest
     * @return
     */
    @PostMapping("/online")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> onlineInterfaceInfo(@RequestBody IdRequest idRequest) {

        long interfaceID = idRequest.getId();
        if (idRequest == null || interfaceID <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //判断接口是否存在
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(interfaceID);
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "接口不存在");
        }

        //todo 判断接口是否能被调用
      /*  //判断接口是否允许被调用
        com.zx.zxapiclientsdk.model.User user = new com.zx.zxapiclientsdk.model.User();
        user.setUsername("ceshi");
        String username = zxAPIClient.getUserNameByPost(user);
        if (StringUtils.isBlank(username)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口不可以被调用");
        }
*/
        //将该接口的状态设置为1
        InterfaceInfo interfaceInfo1 = new InterfaceInfo();
        interfaceInfo1.setId(interfaceID);
        interfaceInfo1.setStatus(InterfaceInfoStatusEnum.ONLINE.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo1);
        return ResultUtils.success(result);

    }

    /**
     * 下线接口
     *
     * @param idRequest
     * @return
     */
    @PostMapping("/offline")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> offlineInterfaceInfo(@RequestBody IdRequest idRequest) {

        long interfaceID = idRequest.getId();
        if (idRequest == null || interfaceID <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //判断接口是否存在
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(interfaceID);
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "接口不存在");
        }

        //将该接口的状态设置为0
        InterfaceInfo interfaceInfo1 = new InterfaceInfo();
        interfaceInfo1.setId(interfaceID);
        interfaceInfo1.setStatus(InterfaceInfoStatusEnum.OFFLINE.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo1);
        return ResultUtils.success(result);
    }


    /**
     * 获取全站可调用接口数
     *
     * @return
     */
    @GetMapping("/getInterfaceCount")
    public BaseResponse getInterfaceCount() {
        return ResultUtils.success(interfaceInfoService.count(new QueryWrapper<InterfaceInfo>().eq("isDelete", 0).eq("status", 1)));
    }

    /**
     * 获取订单页面所需要的接口信息
     * @param availablePiecesTo
     * @return
     */
    @PostMapping("/getOrderInterfaceInfo")
    public BaseResponse getOrderInterfaceInfo(@RequestBody GetAvailablePiecesTo availablePiecesTo){
        return ResultUtils.success(interfaceInfoService.getById(availablePiecesTo.getInterfaceId()));
    }


}
